from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from ershou import models
from elasticsearch import Elasticsearch
from elasticsearch import helpers


# Create your views here.
def index(request):
    return render(request,'index1.html')

def data(request):
    search = request.GET.get('search','')
    data_list = models.Hosemsg.objects.filter(title__contains=search)
    lst = []
    for data in data_list:
        lst.append([data.longitude,data.latitude,data.title])
    dic = {"data":lst}
    return JsonResponse(dic)


##########################ElasticSearch####################################
RESPONSE_DICT = {"status": 200, "total": 0, "data": None, "msg":None}
ES_DB = "lj_index"


def esbody(content):
    if not content:
        content = ""

    body = {
        "query": {
            "bool": {
                "must": [
                    {
                        "match": {
                            "title": content
                        }
                    }
                ]
            }
        },
        "size": 10000
    }
    return body
def es_index(request):
    return render(request, 'es.html')
def es(request):
    print("content-method====",request.method )
    if request.method == "GET":
        es = Elasticsearch()
        content = request.GET.get("search")
        print("content", content)
        article_obj = es.search(index=ES_DB, body=esbody(content),
                                filter_path=['hits.hits', 'hits.total'])
        print("es_obj", article_obj)

        total = article_obj.get("hits", "").get("total", "")
        print("total==", total)
        if total:
            house_list = []
            for item in article_obj["hits"]["hits"]:
                obj = item["_source"]
                # house_list.append(obj)
                house_list.append([obj['longitude'], obj['latitude'], obj['title'], obj['areaname']])

            RESPONSE_DICT['status'] = 200
            RESPONSE_DICT['total'] = total
            RESPONSE_DICT['data'] = house_list
            RESPONSE_DICT['msg'] = "successful"
            return JsonResponse(RESPONSE_DICT)
        else:
            RESPONSE_DICT['status'] = 0
            RESPONSE_DICT['total'] = total
            RESPONSE_DICT['data'] = []
            RESPONSE_DICT['msg'] = "搜索到的内容去天堂了^=^|"
            return JsonResponse(RESPONSE_DICT)



def createMap(request):
    body = {
        "mappings": {
            "document": {
                "dynamic": False,
                "properties": {
                    "title": {
                        "type": "text",
                        "analyzer": "ik_max_word",
                        "fields": {
                            "suggest": {
                                "type": "completion",
                                "analyzer": "ik_max_word"
                            }
                        }
                    },
                    "areaname": {
                        "type": "text"
                    },
                    "longitude": {
                        "type": "text"
                    },
                    "latitude": {
                        "type": "text"
                    },
                    "rid": {
                        "type": "long"
                    },
                    "houserecord": {
                        "type": "long"
                    }
                }
            }
        }
    }
    es = Elasticsearch()
    es.indices.create(index=ES_DB, body=body)
    return HttpResponse("create successful")


def db2es(request):
    house_list = models.Hosemsg.objects.all()
    es = Elasticsearch()
    action = (
        {
            "_index": ES_DB,
            "_type": "document",
            "_source": {
                "id": house.pk,
                "title": house.title,
                "areaname": house.areaname,
                "longitude": house.longitude,
                "latitude": house.latitude,
                "rid": house.rid,
                "houserecord": house.houserecord
            }
        } for house in house_list
    )
    helpers.bulk(es, action)
    return HttpResponse("ok  ok  ok")


def suggestContent(request):
    if request.method == "POST":
        content = request.POST.get("content")
        body = {
            "suggest": {
                "text": content,
                "suggest1": {
                    "term": {
                        "field": "title"
                    }
                },
                "suggest2": {
                    "phrase": {
                        "field": "title",
                    }
                },
                "suggest3": {
                    "completion": {
                        "field": "title"
                    }
                }
            }
        }
        es = Elasticsearch()
        word_list = []
        es_obj = es.search(index=ES_DB, body=body)
        suggest_obj = es_obj["suggest"]
        s1_list = suggest_obj["suggest1"]
        if s1_list:
            for item in s1_list:
                option_list = item["options"]
                if option_list:
                    for it in option_list:
                        if it["text"].strip() not in word_list:
                            word_list.append(it["text"].strip())
                            print("111>>>", it["text"].strip())
        s2_list = suggest_obj["suggest2"]
        if s2_list:
            for item2 in s2_list:
                option2_list = item2["options"]
                if option2_list:
                    for it2 in option2_list:
                        if it2["text"].strip() not in word_list:
                            word_list.append(it2["highlighted"].strip())
                            print("222>>>", it2["highlighted"].strip())

        s3_list = suggest_obj["suggest3"]
        if s3_list:
            for item3 in s3_list:
                option3_list = item3["options"]
                if option3_list:
                    for it3 in option3_list:
                        if it3["text"].strip() not in word_list:
                            word_list.append(it3["text"].strip())
                            print("333>>>", it3["text"].strip())
        print(word_list)
        return JsonResponse(word_list, safe=False)

